// pages/result/result.js
const app = getApp();

Page({
  data: {
    isWin: false,
    score: 0,
    level: 1,
    stars: 0,
    isNewRecord: false,
    targetScore: 1000,
    bestScore: 0
  },

  onLoad(options) {
    const isWin = options.win === 'true';
    const score = parseInt(options.score) || 0;
    const level = parseInt(options.level) || 1;
    const isNewRecord = options.newRecord === 'true';
    const targetScore = 1000 + (level - 1) * 200;
    const bestScore = app.globalData.bestScores[level] || 0;
    
    let stars = 0;
    if (isWin) {
      if (score >= targetScore * 1.5) stars = 3;
      else if (score >= targetScore * 1.2) stars = 2;
      else if (score >= targetScore) stars = 1;
    }

    this.setData({
      isWin,
      score,
      level,
      stars,
      isNewRecord,
      targetScore,
      bestScore
    });

    // 播放结果动画
    setTimeout(() => {
      this.playResultAnimation();
    }, 500);
  },

  playResultAnimation() {
    // 创建星星动画
    if (this.data.stars > 0) {
      for (let i = 0; i < this.data.stars; i++) {
        setTimeout(() => {
          this.animateStar(i);
        }, i * 300);
      }
    }
  },

  animateStar(index) {
    const animation = wx.createAnimation({
      duration: 600,
      timingFunction: 'ease-out'
    });
    
    animation.scale(1.5).step();
    animation.scale(1).step();
    
    this.setData({
      [`starAnimation${index}`]: animation.export()
    });
  },

  playAgain() {
    wx.redirectTo({
      url: `/pages/game/game?level=${this.data.level}`
    });
  },

  nextLevel() {
    if (this.data.level < 20) {
      wx.redirectTo({
        url: `/pages/game/game?level=${this.data.level + 1}`
      });
    } else {
      wx.showToast({
        title: '恭喜通关所有关卡！',
        icon: 'success'
      });
    }
  },

  selectLevel() {
    wx.redirectTo({
      url: '/pages/levels/levels'
    });
  },

  backToHome() {
    wx.reLaunch({
      url: '/pages/index/index'
    });
  },

  shareResult() {
    const shareText = this.data.isWin 
      ? `我在消消乐第${this.data.level}关获得了${this.data.score}分，获得${this.data.stars}星评价！`
      : `我在消消乐第${this.data.level}关获得了${this.data.score}分，再接再厉！`;
    
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
    
    wx.showToast({
      title: '点击右上角分享',
      icon: 'none'
    });
  },

  onShareAppMessage() {
    const shareText = this.data.isWin 
      ? `我在消消乐第${this.data.level}关获得了${this.data.score}分！`
      : `我在消消乐第${this.data.level}关挑战中，一起来玩吧！`;
    
    return {
      title: shareText,
      path: `/pages/game/game?level=${this.data.level}`,
      imageUrl: '' // 可以添加自定义分享图片
    };
  }
})